using System;
using System.Xml;

namespace Daenet.Syndication
{
    public class SyndicationLink
    {
        #region Member Fields

        private Uri m_Uri;

        private string m_RelationshipType;

        private string m_MediaType;

        private string m_Language;

        private long m_Length;

        #endregion

        #region Member Properties

        public Uri Uri
        {
            get { return m_Uri; }
            set { m_Uri = value; }
        }

        public Int64 Length
        {
            get { return m_Length; }
            set { m_Length = value; }
        }

        public string RelationshipType
        {
            get { return m_RelationshipType; }
            set { m_RelationshipType = value; }
        }

        public string MediaType
        {
            get { return m_MediaType; }
            set { m_MediaType = value; }
        }

        public string Title
        {
            get { return m_Language; }
            set { m_Language = value; }
        }

        #endregion

        #region Member Methods

        public SyndicationLink(Uri uri)
        {
            m_Uri = uri;
        }

        internal static SyndicationLink TryParse(XmlReader reader)
        {
            string url = reader.GetAttribute("href") ?? string.Empty;
            SyndicationLink link = new SyndicationLink(new Uri(url, UriKind.RelativeOrAbsolute));
            if (reader.AttributeCount > 1)
            {
                link.RelationshipType = reader.GetAttribute("rel") ?? string.Empty;
                link.MediaType = reader.GetAttribute("type") ?? string.Empty;
                link.Title = reader.GetAttribute("title") ?? string.Empty;
                long length;
                try
                {
                    length = long.Parse(reader.GetAttribute("length"));
                }
                catch (ArgumentNullException)
                {
                    // If the conversion fails, the value is equalized to -1
                    // Note: If the "length" attribute does not exists
                    length = -1L;
                }
                catch(FormatException)
                {
                    // If the conversion fails, the value is equalized to -1
                    // Note: If the "length" attribute is not in the correct format
                    length = -1L;
                }
                catch(OverflowException)
                {
                    // If the conversion fails, the value is equalized to -1
                    // Note: if "length" represents a number less than MinValue
                    // or greater than MaxValue
                    length = -1L;
                }
                //long.TryParse(reader.GetAttribute("length"), out length);
                link.Length = length;
            }
            return link;
        }

        #endregion
    }
}
